import axios from 'axios'

export const ERROR_MSG = 'ERROR_MSG'
export const TO_REGISTRY = 'TO_REGISTRY'
export const LOAD_DATA = 'LOAD_DATA'
export const AUTH_SUCCESS = 'AUTH_SUCCESS'
export const LOGOUT = 'LOGOUT'
export const TO_UPDATEINFO='TO_UPDATEINFO'


function errorMsg(msg) {
    return {
        type: ERROR_MSG,
        msg: msg
    }
}

function authSuccess(data) {
    // console.log(data)
    return {
        type: AUTH_SUCCESS,
        payload: data
    }
}

//登录
export function login({user, pwd}) {
    if (!user || !pwd) {
        return errorMsg('用户名密码必须输入')
    }
    return dispatch => {
        axios.post('/user/login', {user, pwd})
            .then(res => {
                if (res.status === 200 && res.data.code === 0) {
                    dispatch(authSuccess(res.data.data))
                } else {
                    dispatch(errorMsg(res.data.msg))
                }
            })
    }

}

//注册
export function register({user, pwd, repeatpwd, type}) {
    if (!user || !pwd || !repeatpwd) {
        return errorMsg('用户名密码必须输入')
    }
    if (pwd !== repeatpwd) {
        return errorMsg('两次输入的密码不一致')
    }
    return dispatch => {
        axios.post('/user/register', {user, pwd, type})
            .then(res => {
                if (res.status === 200 && res.data.code === 0) {
                    dispatch(authSuccess({user, pwd, type}))
                } else {
                    dispatch(errorMsg(res.data.msg))
                }
            })
    }
}

//完善信息
export function update(data) {
    return dispatch => {
        axios.post('/user/update', data)
            .then(res => {
                if (res.status === 200 && res.data.code === 0) {
                    dispatch(authSuccess(res.data.data))
                } else {
                    dispatch(errorMsg(res.data.msg))
                }
            })
    }
}

export function toUpdateInfo(){
    return{
        type:TO_UPDATEINFO
    }
}



export function logoutSubmit() {
    return {
        type: LOGOUT
    }
}


//加载数据
export function loadData(userinfo) {
    return {
        type: LOAD_DATA,
        payload: userinfo
    }
}

//跳转到registry
export function toRegistry() {
    return {
        type: TO_REGISTRY,
        payload: {msg: ''}
    }
}